﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

namespace SingleUserMall.Web.Controllers
{
    public class AddressController : ApiController
    {
        [HttpGet]
        public List<string> GetLocationByQQ(double lat, double lng)
        {
            List<string> results = new List<string>();
            string requesturl = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&coord_type=5&key=VPLBZ-O4VCX-DO347-7IQB6-FIBPZ-YPFU3&output=jsonp";
            WebRequest request = WebRequest.Create(@requesturl);
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            StreamReader reader = new StreamReader(stream, encode);
            string read = reader.ReadToEnd();
            reader.Close();
            string tt = read.Trim(')').Replace("QQmap&&QQmap(", "");
            var result = (JObject)JsonConvert.DeserializeObject(tt);
            if (result == null || result["result"] == null || result["result"]["ad_info"] == null|| result["result"]["ad_info"]["adcode"] == null)
                return results;
            var code = Convert.ToString(result["result"]["ad_info"]["adcode"]);
            var codeValue = Convert.ToString(result["result"]["address_component"]["district"]);
            results.Add(code);
            results.Add(codeValue.Substring(0,codeValue.Length-1));
            return results;
        }


        [HttpGet]
        public List<string> GetLocationByQQName(string name)
        {
            List<string> results = new List<string>();
            string requesturl = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + name + "&key=VPLBZ-O4VCX-DO347-7IQB6-FIBPZ-YPFU3&output=jsonp";
            WebRequest request = WebRequest.Create(@requesturl);
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            StreamReader reader = new StreamReader(stream, encode);
            string read = reader.ReadToEnd();
            reader.Close();
            string tt = read.Trim(')').Replace("QQmap&&QQmap(", "");
            var result = (JObject)JsonConvert.DeserializeObject(tt);
            if (result == null || result["result"] == null || result["result"]["location"] == null)
                return results;
            var lng = Convert.ToString(result["result"]["location"]["lng"]);
            var lat = Convert.ToString(result["result"]["location"]["lat"]);
            results.Add(lng);
            results.Add(lat);
            return results;
        }
    }
}
